//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package main

import (
	"net/http"

	"atomgit.com/openlinksaas/sql-proxy/gen_code"
	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
)

func NewRouter(routers ...gen_code.Router) *mux.Router {
	router := mux.NewRouter().StrictSlash(true)
	for _, api := range routers {
		for _, route := range api.Routes() {
			var handler http.Handler
			handler = route.HandlerFunc
			handler = handlers.CORS(handlers.AllowedOrigins([]string{"*"}),
				handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "OPTIONS"}),
				handlers.AllowedHeaders([]string{"*"}),
			)(handler)
			handler = handlers.RecoveryHandler()(handler)

			router.
				Methods(route.Method).
				Path(route.Pattern).
				Name(route.Name).
				Handler(handler)
		}
	}

	return router
}

type OptionsHandler struct{}

func (h *OptionsHandler) ServeHTTP(writer http.ResponseWriter, _req *http.Request) {
	header := writer.Header()
	header.Set("Access-Control-Allow-Origin", "*")
	header.Set("Access-Control-Request-Headers", "*")
	header.Set("Access-Control-Allow-Headers", "*")
	writer.WriteHeader(200)
}
